import { PageDto } from './../user/dto/page.dto';
import { HttpException, Injectable, Logger } from '@nestjs/common';
import axios from 'axios';
import { askQuestionDto, changeGroupNameDto, saveMessageDto } from './dto/chat-api.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { GptMessage } from './entities/gptMessage.entity';
import { FindOptionsWhere, ILike, Like, Repository } from 'typeorm';
import { GptGroup } from './entities/gptgroup.entity';
import { group } from 'console';
import { UserEntity } from '../user/entities/user.entity';
import { Configuration, OpenAIApi } from 'openai';

let API_KEY = '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';
@Injectable()
export class ChatApiService {
  // @InjectRepository(UserEntity) private userModel: Repository<UserEntity>,
  constructor(
    @InjectRepository(GptMessage) private messageModel: Repository<GptMessage>,
    @InjectRepository(GptGroup) private gptGroupModel: Repository<GptGroup>,
  ) {
    
  }

 
  /**
   * @author nie
   * @description 保存消息记录
   * @email a896211755@gmail.com
   */
  async saveMessage(body :saveMessageDto) {
    const val = new GptMessage();
    val.question = body.question;
    val.answer = body.answer;
    val.gptGroup_id = body.group_id;
    val.createdDate = body.createdDate
    return await this.messageModel.save(val);
  }
  /**
   * @author nie
   * @description 获取聊天组下的聊天记录
   * @email a896211755@gmail.com
   */
  async getMessageByGroupId(group_id: number, page: PageDto) {
    const { pageNum, pageSize } = page;
    const skip = (pageNum - 1) * pageSize;
    const result = await this.messageModel.findAndCount({
      select: ['createdDate', 'question', 'answer'],
      where: { gptGroup_id: group_id },
      skip,
      take: pageSize,
      order: {
        createdDate: 'asc',
        // @Column({comment:"收藏"})
      },
    });
    console.log(result);
    return {
      list: result[0],
      count: result[1],
    };
  }
/**
* @author nie
* @description 添加聊天组 
* @email a896211755@gmail.com
*/
  async addGroup(id: number) {
    return await this.gptGroupModel.createQueryBuilder().insert().values({ user_id: id, title: '新会话' }).execute();
  }

  /**
   * @author nie
   * @description 获取用户下的消息组
   * @email a896211755@gmail.com
   */
  async getGroupList(id: number, page: PageDto,name) {
    const { pageSize, pageNum } = page;
    const skip = (pageNum - 1) * pageSize;
    let where :FindOptionsWhere<GptGroup> ={
      user_id:null,
      // title:''
    }
    if(name){
       where.title = ILike(`%${name}%`)
    }
    where.user_id = id
    console.log(where)
    return await this.gptGroupModel.findAndCount({
      where,
      select: ['id', 'conversation_id', 'createdDate', 'title','collection'],
      skip,
      take: pageSize,
      order:{
        collection:"ASC"
      }
    });
  }
  async groupAddConversation_id(group_id: number, conversation_id: any) {
    let result: GptGroup = await this.gptGroupModel.findOne({ where: { id: group_id } });
    result.conversation_id = conversation_id;
    await this.gptGroupModel.save(result);
  }
  async getAnswer(data: askQuestionDto) {
    const val = await axios
      .post(
        'https://api.zhishuyun.com/chatgpt?token=ea160893d61b4096882a7bcc769a2bc3',
        { question: data.question, stateful: true, conversation_id: data.conversation_id },
        {
          headers: {
            // accept: 'application/x-ndjson',
            'content-type': 'application/json',
          },
        },
      )
      .catch((error) => {
        console.log(error);
        return {
          status: 500,
          data: '',
        };
      });
    // console.log(val);
    if (val.status == 200) {
      return val;
    } else {
      return false;
    }
  }
  /**修改群组标题 */
  async changeGroupName(query :changeGroupNameDto){
   let result =  await this.gptGroupModel.findOne({
        where:{
          id:query.group_id
        }
      })
     if(result.id>0){
          result.title = query.title
         return await this.gptGroupModel.save(result)
     }else{
        throw new HttpException({code:0,message:"未找到群组"},200)
     }
  }
  /** 删除聊天组 */
  async deleteMessageGroup(group_id: number,user_id :number) {
   let [result,count] = await this.gptGroupModel.findAndCount({
      where:{
        user_id
      }
    })
    if(count==1){
      throw new HttpException({code:0,message:"不可删除"},200)
    }
    try {
      (await this.messageModel.delete({ gptGroup_id: group_id })).affected;
      (await this.gptGroupModel.delete({ id: group_id })).affected;
    } catch (error) {
      throw error;
    }
    return true;
  }


  /** 收藏聊天组 */
  async collectGroup(val :1|2,group_id :number){
    
   let result = await this.gptGroupModel.findOne({
      where:{
        id:group_id
      }
    })
    result.collection = val
   await this.gptGroupModel.save(result)

  }

}

function entityManager() {
  throw new Error('Function not implemented.');
}
